package service

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type jwtService struct {
}

type claims struct {
	Id         int64  `json:"id"`
	Username   string `json:"username"`
	SchoolName string `json:"school_name"`
	SchoolId   int64  `json:"school_id"`
	RoleId     int64  `json:"role_id"`
	IsAdmin    int    `json:"is_admin"`
	jwt.StandardClaims
}

var secret = []byte("yiran@123!@#")

// CreateToken 创建token
func (j jwtService) CreateToken(id int64, username string, schoolName string, schoolId int64, roleId int64, isAdmin int) (string, error) {
	nowTime := time.Now()
	expireTime := nowTime.Add(30 * 24 * time.Hour)
	claims := claims{
		id,
		username,
		schoolName,
		schoolId,
		roleId,
		isAdmin,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "admin",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(secret)
	return token, err
}

// ValidateToken token检验
func (j jwtService) ValidateToken(signToken string) (*claims, error) {
	token, err := jwt.ParseWithClaims(signToken, &claims{}, func(token *jwt.Token) (interface{}, error) {
		return secret, nil
	})

	if err != nil {
		return nil, err
	}

	//令牌有效
	claims, ok := token.Claims.(*claims)
	if ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("token无效")
}

func NewJwtService() *jwtService {
	return &jwtService{}
}
